<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :visible="dialogVisible"
    custom-class="firber-dialog"
    :title="$t('BIND_AREA')"
    :width="setDialogWidth('450px')"
    @close="close"
  >
    <el-form
      ref="bindAreaForm"
      :model="bindAreaForm"
      :rules="bindAreaRules"
      label-width="auto"
      class="pr-10"
      style="height: 400px;"
    >
      <el-form-item :label="$t('ORGANIZATION_NAME')" prop="orgId">
        {{ bindAreaForm.orgName }}
      </el-form-item>
      <el-form-item :label="$t('AREA_NAME')" prop="regionIds">
        <div>
          <el-input
            v-model="filterAreaKeywords"
            :placeholder="this.$t('ENTER_NAME', { msg: this.$t('AREA_NAME')})"
            size="mini"
            style="margin-bottom: 6px"
            suffix-icon="el-icon-search"
          />
          <el-tree
            ref="areaTree"
            node-key="key"
            v-bind="$attrs"
            show-checkbox
            class="a-area-tree"
            :check-strictly="false"
            accordion
            :default-checked-keys="regionIds"
            :data="areaTree"
            style="background-color: transparent !important"
            :filter-node-method="filterRegion"
            v-on="$listeners"
          />
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="close">{{ $t('CANCEL') }}</el-button>
      <el-button type="primary" @click="bindArea('bindAreaForm')">{{ $t('CONFIRM') }}</el-button>
    </template>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { buildTree, getParentsById, deepClone } from '@/utils/common'
  import { difference, uniq } from 'lodash'
  import regionApi from '@/api/basebiz/RegionApi'
  import OrgRegionApi from '@/api/basebiz/OrgRegionApi.js'
  import OperateLogApi from '@/api/system/OperateLogApi.js'

  export default {
    props: {
      bindAreaForm: {
        type: Object,
        default: () => {}
      },
      dialogVisible: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        filterAreaKeywords: '',
        areas: [],
        bindAreaRules: {
          orgId: [
            {
              required: true,
              message: this.$t('SELECT_NAME', { msg: this.$t('ORGANIZATION_NAME') }),
              trigger: 'blur'
            }
          ],
          regionIds: [
            {
              required: false,
              message: this.$t('SELECT_NAME', { msg: this.$t('AREA_NAME') }),
              trigger: 'change'
            }
          ]
        },
        regionIds: [],
        checks: [],
        areaTree: []
      }
    },
    computed: {
      ...mapGetters(['regionTree', 'baseRegionList', 'getUserId', 'getUser'])
    },
    watch: {
      filterAreaKeywords(val) {
        this.$refs.areaTree.filter(val)
      }
    },
    created() {
      this.areaTree = deepClone(this.regionTree)
      OrgRegionApi.regionAuth({ orgId: this.bindAreaForm.orgId }).then(res => {
        this.regionIds = res || []
        this.checks = res.filter(
          funcId =>
            this.$refs.areaTree.getNode(funcId) &&
            this.$refs.areaTree.getNode(funcId).childNodes.length === 0
        )
      })
      // 如果机构类型是平台机构，则默认区域全选且为只读状态
      if (this.bindAreaForm.orgType === 'PLATFORM') {
        console.log('走这个了')
        regionApi.list().then(res => {
          if (!res) return
          this.regionIds = res.map(i => i.regionId)
        })
        this.filterTree(this.areaTree)
      }
    },
    methods: {
      close() {
        this.$emit('update:dialogVisible', false)
      },
      filterRegion(value, data) {
        if (!value) return true
        // 如果是多级结构，选择了某一级，把其子级也带出来
        if (data.label.indexOf(value) !== -1) {
          if (data.children && data.children.length) {
            data.children.forEach((ele) => {
              ele.parent = data.label
              ele.children &&
                ele.children.forEach((ele1) => {
                  ele1.parent = data.label
                })
            })
          }
        }
        return (
          data.label.indexOf(value) !== -1 ||
          (data.parent && data.parent.indexOf(value) !== -1)
        )
      },
      bindArea(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addLog(true)
            OrgRegionApi.bindOrg({
              orgName: this.bindAreaForm.orgName,
              orgId: this.bindAreaForm.orgId,
              regionIds: [...this.$refs.areaTree.getCheckedKeys()],
              halfRegionIds: [...this.$refs.areaTree.getHalfCheckedKeys()]
            }).then(res => {
              if (res) {
                this.$message.success(this.$t('SAVE_SUCCESS'))
              } else {
                this.$message.error(this.$t('SAVEFAILED'))
              }
              this.close()
            })
          }
        })
      },
      addLog(result = true) {
        // 对比前后变化
        const newChecks = this.$refs.areaTree.getCheckedKeys().filter(
          funcId =>
            this.$refs.areaTree.getNode(funcId) &&
            this.$refs.areaTree.getNode(funcId).childNodes.length === 0
        )
        const diffChecks = uniq(difference(newChecks, this.checks).concat(difference(this.checks, newChecks)))
        // 判断两个两个数组差项是新增还是减少
        const addChecks = [] // 存增加的
        const reduceChecks = [] // 存减少的
        diffChecks.forEach(i => {
          if (this.checks.includes(i)) {
            reduceChecks.push(i)
          }
          if (newChecks.includes(i)) {
            addChecks.push(i)
          }
        })
        // 取消了哪些
        let reduceChecksStr = ''
        reduceChecks.forEach(i => {
          const parentList = (getParentsById(this.regionTree, i, 'key') || [])
          if (parentList.length) {
            const parentListStr = parentList.reverse().reduce((prev, cur, index, arr) => {
              if (arr.length - 1 === index) {
                return prev + cur.label
              } else {
                return prev + cur.label + '-'
              }
            }, '')
            reduceChecksStr += this.$t('ORG_AREA_CANCEL_LOG', { regionName: parentListStr })
          }
        })
        // 选中了哪些
        let addChecksStr = ''
        addChecks.forEach(i => {
          const parentList = (getParentsById(this.regionTree, i, 'key') || [])
          if (parentList.length) {
            const parentListStr = parentList.reverse().reduce((prev, cur, index, arr) => {
              if (arr.length - 1 === index) {
                return prev + cur.label
              } else {
                return prev + cur.label + '-'
              }
            }, '')
            addChecksStr += this.$t('ORG_AREA_SELECTED_LOG', { regionName: parentListStr })
          }
        })
        const content = {
          orgName: this.bindAreaForm.orgName,
          orgId: this.bindAreaForm.orgId,
          currentUserId: this.getUserId,
          reduceChecksStr: reduceChecksStr,
          addChecksStr: addChecksStr,
          i18nKey: 'SYSTEM_ORG_AREA_LOG' // 管辖区域日志
        }
        // console.log(reduceChecksStr, addChecksStr)
        // 记录登录日志
        try {
          diffChecks.length && OperateLogApi.addLog({
            api: '/orgRegion/bindOrg',
            item: 'MENU_ORG_MANAGER', // 机构管理
            terminal: 'BIND_AREA', // 管辖区域
            object: this.bindAreaForm.orgName,
            operateResult: result,
            realName: this.getUser.realName,
            content: JSON.stringify(content)
          })
        } catch (error) {
          console.log(error)
        }
      },
      filterTree(tree) {
        tree.forEach(i => {
          if (i.children && i.children.length) {
            i.disabled = true
            this.filterTree(i.children)
          } else {
            i.disabled = true
          }
        })
      }
    }
  }
</script>
